<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/9/13
 * Time: 14:17
 */

namespace App\CronTask;


use App\Enums\UrlEnums;
use App\Library\Auth;
use App\Utility\Pool\MysqlObject;
use App\Utility\Pool\MysqlPool;
use EasySwoole\EasySwoole\Crontab\AbstractCronTask;
use EasySwoole\HttpClient\HttpClient;

/**
 * 更新道具
 * Class RawItemsCron
 * @package App\CronTask
 */
class RawItemsCron extends AbstractCronTask
{
    public static function getRule(): string
    {
        // TODO: Implement getRule() method.
        return '@monthly';
    }
    public static function getTaskName(): string
    {
        // TODO: Implement getTaskName() method.
        return 'RawItems';
    }

    static function run(\swoole_server $server, int $taskId, int $fromWorkerId, $flags = null)
    {
        // TODO: Implement run() method.
        $tables = ['siam_kogitems','siam_dotaitems','siam_lolitems'];
        $path = [UrlEnums::KOG_ITEMS_PATH,UrlEnums::DOTA_ITEMS_PATH,UrlEnums::LOL_ITEMS_PATH];

        for ( $i=0;$i<count($path);$i++ ){
            $url = UrlEnums::FJURL.$path[$i].'?version=2';
            $client = new HttpClient($url);
            list($s1, $s2) = explode(' ', microtime());
            $microtime = (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000); //毫秒时间戳
            $option = [
                'path'      => $path[$i],
                'api_time'  => $microtime
            ];
            $header = Auth::getInstance()->header($option);
            $client->setHeaders($header,true,false);
            $response = $client->get();
            $content = $response->getBody();
            $data = json_decode($content,true);
            MysqlPool::invoke(function (MysqlObject $db)use($data,$tables,$i){
                if( $data['code'] == 200 && !empty($data['data']) ){
                    foreach ( $data['data'] as $item ){
                        $raw = $db->where('item_id',$item['item_id'])->getOne($tables[$i]);
                        if( !$raw ){
                            if( isset($item['is_recipe']) ){
                                $item['is_recipe'] = $item['is_recipe'] == true ? 1 : 0;
                            }
                            if( isset($item['is_secret_shop']) ){
                                $item['is_secret_shop'] = $item['is_secret_shop'] == true ? 1 : 0;
                            }
                            if( isset($item['is_side_shop']) ){
                                $item['is_side_shop'] = $item['is_side_shop'] == true ? 1 : 0;
                            }
                            $res = $db->insert($tables[$i],$item);
                        }
                    }
                }
            });
        }

    }
}